//165
int pl = 8; //low 并行输入（8个io状态存入寄存器内） ，high 串行输出
int cp = 9; //时钟脉冲
int data_in = 10; //数据采集
unsigned long  lastdata = 0; //最终采集到的数据
unsigned long  newdata = 0; //最新采集到的数据
int show_no  = 0; //led显示
unsigned long readbyte() {
  unsigned long byte_temp = 0;
  long byte_ ;
  digitalWrite(pl, LOW);
  delayMicroseconds(5);
  digitalWrite(pl, HIGH); //从D7开始读取至D0
  for (int i = 0; i < 8; i++) { //从D0开始高位 D7是结束低位
    byte_ = digitalRead(data_in);
    byte_temp |= (byte_ << i);
    digitalWrite(cp, HIGH);
    delayMicroseconds(5);
    digitalWrite(cp, LOW);

  }
  return byte_temp;

}


//595
int ds = 5;
int sh_cp = 6;
int st_cp = 7;

int a[11][8] = {
  { 1, 1, 1, 1, 1, 1, 0, 0},
  { 0, 1, 1, 0, 0, 0, 0, 0},
  { 1, 1, 0, 1, 1, 0, 1, 0},
  { 1, 1, 1, 1, 0, 0, 1, 0},
  { 0, 1, 1, 0, 0, 1, 1, 0},
  { 1, 0, 1, 1, 0, 1, 1, 0},
  { 1, 0, 1, 1, 1, 1, 1, 0},
  { 1, 1, 1, 0, 0, 0, 0, 0},
  { 1, 1, 1, 1, 1, 1, 1, 0},
  { 1, 1, 1, 1, 0, 1, 1, 0},
  { 0, 0, 0, 0, 0, 0, 0, 0}
};


void led_on(int p ) {
  digitalWrite(st_cp, LOW);
  int left  = p / 10 % 10;
  int right  = p % 10 ;
  //先高位（左）
  for (int x = 0 ; x < 8; x++) {
    digitalWrite(sh_cp, LOW);
    digitalWrite (ds, a[left][x]);
    digitalWrite(sh_cp, HIGH);
  }
  //在低位（右）
  for (int x = 0 ; x < 8; x++) {
    digitalWrite(sh_cp, LOW);
    digitalWrite (ds, a[right][x]);
    digitalWrite(sh_cp, HIGH);
  }
  digitalWrite(st_cp, HIGH);
}
void setup() {
  Serial.begin(9600);
  //165
  pinMode(pl, OUTPUT);
  pinMode(cp, OUTPUT);
  pinMode(data_in, INPUT);
  digitalWrite(pl, HIGH);
  digitalWrite(cp, LOW);
  //595
  pinMode(ds, OUTPUT);
  pinMode(sh_cp, OUTPUT);
  pinMode(st_cp, OUTPUT);
  lastdata = readbyte();
  // put your setup code here, to run once:

}

void loop() {
  newdata = readbyte();
  if (newdata != lastdata) {
    lastdata = newdata;
    Serial.println(lastdata, BIN);
    if (lastdata == 0B01111111) {
      show_no = 1;
    }
    else  if (lastdata == 0B10111111) {
      show_no = 2;
    }
    else  if (lastdata == 0B11011111) {
      show_no = 3;
    }
    else  if (lastdata == 0B11101111) {
      show_no = 4;
    }
    else  if (lastdata == 0B11110111) {
      show_no = 5;
    }
    else  if (lastdata == 0B11111011) {
      show_no = 6;
    }
    else  if (lastdata == 0B11111101) {
      show_no = 7;
    }
    else  if (lastdata == 0B11111110) {
      show_no = 8;
    }
    else  if (lastdata == 0B01111110) {
      show_no = 9;
    }

    led_on (show_no);
  }
  delay(10);
  // put your main code here, to run repeatedly:

}